<?php
include_once "baseChannel.php";

class flowRecharge2 extends baseChannel
{
    protected $appId;
    protected $appSecret;
    protected $shopOpenId;

    public function __construct($setting)
    {
        parent::__construct($setting);
        $this->appId = $setting['appId'];
        $this->appSecret = $setting['appSecret'];
        $this->shopOpenId = $setting['shopOpenId'];
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        $city = explode('-', $params['area_name'])[1];
        $map = [
            "深圳" => "sz",
            "东莞" => "dg",
            "广州" => "gz",
        ];
        $timestamp = $this->getCurDate();
        $serial = $this->getCurDate() + rand(1, 9999);
        $header = [
            "appId:" . $this->appId,
            "timestamp:" . $timestamp,
            "serial:" . $serial,

        ];
        $city = $map[$city] ?? "all";
        $data = [
            "shopOpenId" => $this->shopOpenId,
            "productId" => $code,
            "mobile" => $mobile,
            "city" => $city,  //传all
        ];
        // "Content-Type:application/json"
        $sign = $this->getSign([
            "appId" => $this->appId,
            "shopOpenId" => $this->shopOpenId,
            "timestamp" => $timestamp,
            "serial" => $serial,
            "productId" => $code,
            "mobile" => $mobile,
            "city" => $city,
        ]);
        array_push($header, "sign:" . $sign);
        // var_dump($header);

        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data, '', '', $header);
        $return_data = json_decode($return_str, 1);
        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['orderNo'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' =>  null,
            'channel_balance' =>  null,
        ];

        if ($return_data['code'] == 10000) {
            // 成功
            // $ret['error'] = 0;
            // $ret['order_status'] = 3;
            // $ret['msg'] = $return_data['data']['description'] ?? '下单成功';
            $ret['error'] = 0;
            $ret['msg'] = $return_data['ResultDesc'] ?? '下单成功';
        } else {
            // 失败
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['ResultDesc'] ?? '下单失败';
            }
        }
        return $ret;
        // return;
    }
    public function callback($params)
    {
        $this->callback_params = $params;
        $this->channel_order_sn = $params['orderNo'];
        $this->push_order_sn = "";
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $params['orderStatus'];
        $msg = $params['description'];
        //凭证
        // $pz =  $params['refid'] ?? '';
        // $res['voucher'] = $pz;
        // 验证签名
        // $sign = $this->getSign($params);
        // if ($pz) {
        //     $singStr = $this->agent . $params['out_order_no'] . $params['order_no'] . $params['amount'] . $params['agent_price'] . $params['status'] . $params['refid'] . $this->appSecret;
        // } else {
        //     $singStr = $this->agent . $params['out_order_no'] . $params['order_no'] . $params['amount'] . $params['agent_price'] . $params['status'] . $this->appSecret;
        // }
        // $sign = md5($singStr);
        // if ($sign !== $params['sign']) {
        //     $res['error'] = 1;
        //     $res['msg'] = '签名不匹配';
        //     $res['resp_data'] = 'fail';
        //     $res['sign'] = $sign;
        //     return $res;
        // }
        if ($order_status == 1) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $msg ?? '充值完成';
            $res['resp_data'] = 'ok';
        }
        if ($order_status == 2) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $msg ?? '充值失败';
            $res['resp_data'] = 'FAIL';
        }
        //初始化就是充值中
        // if ($order_status == 10) {
        //     $res['order_status'] = 2;
        //     $res['msg'] = $msg ?? '充值中';
        // }
        return $res;
    }
    // public function getSign2($str, $appSecret)
    // {
    //     $sign = openssl_encrypt($str, "AES-128-ECB", ($appSecret), OPENSSL_RAW_DATA);
    //     $sign = base64_encode($sign);
    //     return $sign;
    // }
    public function getSign($data, $emptyWithSign = false)
    {
        foreach ($data as $key => $val) {
            if (!$emptyWithSign) {
                if (empty($val)) {
                    unset($data[$key]);
                }
            }
            if (isset($data['sign'])) {
                unset($data['sign']);
            }
        }
        ksort($data);
        $str = http_build_query($data);
        // var_dump(111);
        // var_dump($str);
        // var_dump(base64_encode($this->appSecret));
        $sign = openssl_encrypt($str, "AES-128-ECB", base64_decode($this->appSecret), OPENSSL_RAW_DATA);
        $sign = base64_encode($sign);
        // $sign = md5($str);
        return $sign;
    }
    public function queryOrder($params)
    {
        $url = $this->query_order_url;
        $post_data = [
            'shopOpenId' => $this->shopOpenId,
            'orderNo' => $params['channel_order_sn'],
        ];
        $timestamp = $this->getCurDate();
        $serial = $this->getCurDate() + rand(1, 9999);
        $header = [
            "appId:" . $this->appId,
            "timestamp:" . $timestamp,
            "serial:" . $serial,

        ];
        $sign = $this->getSign([
            "appId" => $this->appId,
            "timestamp" => $timestamp,
            "serial" => $serial,
            "shopOpenId" => $this->shopOpenId,
            "orderNo" => $params['channel_order_sn'],
        ]);
        array_push($header, "sign:" . $sign);

        // $post_data['sign'] = $sign;

        $return_str = $this->httpRequest($url, 'POST', $post_data, '', '', $header);
        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' =>  '', //凭证
            'post_data' => json_encode($post_data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        //充值中
        // if ($return_data['nRtn'] == 5011 || $return_data['nRtn'] == 5019) {
        //     $ret['msg'] = '充值中:' . $return_data['szRtnCode'];
        // }
        // 成功
        if ($return_data['code'] == 10000  && $return_data['data']['orderStatus'] == 1) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '充值完成:' . $return_data['description'];
        }
        // 失败
        if ($return_data['code'] == 10000 && $return_data['data']['orderStatus'] == 2) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '充值失败:' . $return_data['description'];
        }
        return $ret;
    }
    //获取当前时间的毫秒
    public function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }
    // 获取当前时间包括毫秒
    public function getCurDate($isSecond = false)
    {
        if ($isSecond) {
            return time();
        } else {
            $time = $this->msectime();
            $timestamp = time() . substr($time, -3);
            return $timestamp;
        }
    }
}
